package com.example.elysiumease.controller;

import com.example.elysiumease.exception.BusinessException;
import com.example.elysiumease.mapper.SinMapper;
import com.example.elysiumease.model.Sin;
import com.example.elysiumease.result.ResponseResult;
import jakarta.validation.constraints.Min;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/api/sins")
@Validated
@Slf4j
public class SinController {
    //postman测试完成
    @Autowired
    private SinMapper sinMapper;

    @PostMapping
    public ResponseResult<Short> createSin(
            @Validated @RequestBody Sin sin) {
        if (sinMapper.insertSin(sin) <= 0) {
            throw new BusinessException("罪行类型创建失败");
        }
        return ResponseResult.success(sin.getSinId());
    }

    @GetMapping("/{id}")
    public ResponseResult<Sin> getSin(
            @PathVariable @Min(1) Short id) {
        Sin sin = sinMapper.selectById(id);
        if (sin == null) {
            throw new BusinessException(404, "罪行类型不存在");
        }
        return ResponseResult.success(sin);
    }

    @PutMapping("/{id}")
    public ResponseResult<Void> updateSin(
            @PathVariable @Min(1) Short id,
            @Validated @RequestBody Sin sin) {
        sin.setSinId(id);
        if (sinMapper.updateSin(sin) <= 0) {
            throw new BusinessException("罪行类型更新失败");
        }
        return ResponseResult.success();
    }

    @DeleteMapping("/{id}")
    public ResponseResult<Void> deleteSin(
            @PathVariable @Min(1) Short id) {
        if (sinMapper.deleteSin(id) <= 0) {
            throw new BusinessException("罪行类型删除失败");
        }
        return ResponseResult.success();
    }
}